import errorCodesBuilder from '../../helpers/errorCodesBuilder';
import { TASK_KEY_LABEL_MAP } from '../../../common/constants';
const errorCodes = errorCodesBuilder('停止任务失败');

export default {
	description: '停止任务',
	type: 'Task',
	args: {
		taskId: 'MongoID!',
	},
	async resolve(root, { taskId }, { request }) {
		const {
			headers: { cookie },
			server: {
				methods: { stopTaskSession },
				app: {
					model: { Task },
				},
			},
			auth: {
				credentials: { permissionMap, uid },
			},
		} = request;

		let task;
		let note = '';
		try {
			const query = { _id: taskId };
			if (!permissionMap[`cloud-monitor\x01editTask\x010`]) {
				query.uid = uid;
			}
			task = await Task.findOne(query).populate({
				path: 'jobId',
				populate: { path: 'jobId' },
			});
			note = task.jobId.note;
			if (!task) {
				throw new Error(`stopTask: not found task ${task} with uid ${uid}`);
			}
		} catch (err) {
			const error = errorCodes['[01]终止任务:查找任务mongo记录失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		try {
			await stopTaskSession({
				cookie,
				jobId: task.jobId?._id,
				taskSessionIds: [task.taskSessionId],
			});
		} catch (err) {
			const error = errorCodes['[01]停止任务：删除任务失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		request.log.audit(
			{
				affects: [task.target],
				module: 'task',
				actionType: 'update',
				actionMessage: `更新${TASK_KEY_LABEL_MAP[task.taskType]}监测任务`,
				detail: `停止${
					TASK_KEY_LABEL_MAP[task.taskType]
				}监测任务队列中资产名称为${note}的监测任务。`,
			},
			`[${task.target}]停止监测任务`
		);

		return task;
	},
};
